package com.kedacom.demo.modb.apdbproxy.handler;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.kedacom.demo.modb.ap.dao.APJdbcDaoSupport;
import com.kedacom.demo.modb.rabbitmq.gateway.ModbMessageGateway;
import com.kedacom.demo.modb.rabbitmq.message.CreateAccountEventMessage;
import com.kedacom.demo.modb.rabbitmq.message.CreateAccountSqlAndEventMessage;
import com.kedacom.demo.modb.rabbitmq.message.ModbMessage;

/**
 * {@link ModbMessage}消息处理类
 * @author luocanfeng
 * @date 2013-1-11
 */
@Component("modbMessageHandler")
public class ModbMessageHandler {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Value("#{rabbitmq['rabbitmq.routingkey.event.toprivate']}")
	private String routingKeyToPrivateEvent;

	@Resource
	private APJdbcDaoSupport apJdbcDaoSupport;

	@Resource
	private ModbMessageGateway modbMessageGateway;

	public void handleMessage(CreateAccountSqlAndEventMessage message) {
		logger.debug("Received: {}", ToStringBuilder.reflectionToString(message, ToStringStyle.SHORT_PREFIX_STYLE));

		// FIXME hard coding
		Object createdAt = message.getSqlArgs()[message.getSqlArgs().length - 1];
		message.getSqlArgs()[message.getSqlArgs().length - 1] = new Date((Long) createdAt);
		apJdbcDaoSupport.getJdbcTemplate().update(message.getSql(), message.getSqlArgs());
		logger.debug("Executed sql: \'{}\' with arguments \'{}\'", message.getSql(),
				ToStringBuilder.reflectionToString(message.getSqlArgs(), ToStringStyle.SHORT_PREFIX_STYLE));

		// 消费Sql与事件消息后，向私有云转发事件消息
		CreateAccountEventMessage distributeMessage = new CreateAccountEventMessage(message.getAccountMoid());
		// FIXME hard code
		modbMessageGateway.sendModbMessage(routingKeyToPrivateEvent + ".kedacom", distributeMessage);
	}

}
